package cn.restcloud.springboot.init;

import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.restcloud.gateway.dispatcher.GatewayDispatcher;
import cn.restcloud.springboot.config.SpringbootWebMvcConfig;

public class RestCloudGatewayServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private String rootPath=SpringbootWebMvcConfig.getGatewayRootPath();
	
	private GatewayDispatcher getGatewayDispatcher() {
		return new GatewayDispatcher();
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestUrl=getRequestUrl(request);
		if(RestCloudServlet.asyncsupported.equals("true")){
			//异步请求支持
			AsyncContext asyncContext = request.startAsync(request, response);
			asyncContext.setTimeout(Integer.parseInt(RestCloudServlet.asyncTimeOut)); //默认30秒超时
			RestCloudServlet.getScheduledThreadPoolExecutor().execute(new GatewayDispatcher(asyncContext,requestUrl));
		}else{
			//同步请求支持
			getGatewayDispatcher().execute(request, response,requestUrl, false);
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  doGet(request,response);
	}
  
	@Override
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  doGet(request,response);
	}
	
	@Override
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  doGet(request,response);
	}
	
	/**
	 * 获取请求的服务地址,去掉rootpath前面一段的服务地址
	 * @param request
	 * @return
	 */
	public String getRequestUrl(HttpServletRequest request){
		String url = request.getRequestURI().substring(rootPath.length());//访问地址:http://localhost/restcloud/rest/appid/test.do得到/rest/appid/test.do
		return url;
	}
  
	
}